// Set service path
window.softools = {};
window.softools.servicePath = "https://api.softools.net/";
window.softools.tenant = "demo";
window.softools.token = "";

// Set default headers
var setXhrHeaders = function (jqxhr) {
    jqxhr.setRequestHeader("Cache-Control", "no-transform");
    jqxhr.setRequestHeader("X-Softools-Tenant", window.softools.tenant);
    jqxhr.setRequestHeader("Authorization", "Bearer " + window.softools.token);
    jqxhr.setRequestHeader("Content-Type", "application/json");
    jqxhr.setRequestHeader("Accept", "application/json");
}

// Generic function to handle AJAX errors
var handleAjaxError = function (jqxhr, textStatus, errorThrown) {
    if (jqxhr.readyState == 0 || jqxhr.status == 0) {
        return; //Skip this error
    }
    if (jqxhr.status == 401) {
        alert('Not Authorised');
        return;
    }
    if (jqxhr.status == 400) {
        //Chances are that this is due to validation
        return;
    } else {
        try {
            var error = JSON.parse(jqxhr.responseText);
            var displayText = error.Message;
            if (error.ExceptionMessage && error.ExceptionMessage != error.Message) {
                displayText = displayText + " - " + error.ExceptionMessage;
            }
            alert(displayText);
        } catch (e) {
            var displayText = "An unexpected error occurred - " + errorThrown;
            alert(displayText);
        }
    }
}

// Append headers to all requests
$(document).ajaxSend(function (event, jqxhr, settings) {
    setXhrHeaders(jqxhr);
});


$.support.cors = true;


function appsViewModel() {
    var self = this;

    self.apps = ko.observableArray([]);
//method 1
    self.getApps = function () {
        var url = window.softools.servicePath + "api/apps";
        $.ajax(url, {
            type: 'GET',
            beforeSend: setXhrHeaders
        }).done(function (data) {
            self.apps(ko.mapping.fromJS(data)());
			
        });
    };
//method 2
self.reports = ko.observableArray([]);
    self.getAppReport = function () {
        var url = window.softools.servicePath + "api/apps/pillars/reports/all";
        $.ajax(url, {
            type: 'GET',
            beforeSend: setXhrHeaders
        }).done(function (data1) {
            self.reports(ko.mapping.fromJS(data1)());
        });
    };	
	
	

	}
	
self.toggleCommentSection = function() {
    self.commentsHidden(!self.commentsHidden());
}
	function getAllApps() {
	 var againAuthRequest = function (token) {
        var url = window.softools.servicePath + "token";

        var auth = {
            
            Authentication: "Bearer " +  window.softools.token             
        };

        return $.ajax(url, {
            type: "POST",
            global: false,
            data: auth,
            beforeSend: function (jqxhr) {
                jqxhr.setRequestHeader("Accept", "application/json");
            }
        }).done(function (data) {
            window.softools.token = data.access_token;
			//alert(window.softools.token);
            return true;
        }).fail(function (jqxhr, textStatus, errorThrown) {
            handleAjaxError(jqxhr, textStatus, errorThrown);
            return false;
        });
    }
	againAuthRequest(window.softools.token).then(function (result) {
        //var model = new appsViewModel();
        //model.getApps();
        //ko.applyBindings(model);
    var model1 = new appsViewModel();
	model1.getAppReport();
       ko.applyBindings(model1);
	   
    
	});
	}
	
$(document).ready(function () {


   // Auth request
    var authRequest = function (username, password) {
        var url = window.softools.servicePath + "token";

        var auth = {
            grant_type: "password",
            username: window.softools.tenant + "\\" + username,
            password: password
        };

        return $.ajax(url, {
            type: "POST",
            global: false,
            data: auth,
            beforeSend: function (jqxhr) {
                jqxhr.setRequestHeader("Accept", "application/json");
            }
        }).done(function (data) {
            window.softools.token = data.access_token;
			//alert(window.softools.token);
            return true;
        }).fail(function (jqxhr, textStatus, errorThrown) {
            handleAjaxError(jqxhr, textStatus, errorThrown);
            return false;
        });
    }

    authRequest("\jacka", "sunshine1234").then(function (result) {
	
        var model = new appsViewModel();
        model.getApps();
        ko.applyBindings(model);
   // var model1 = new appsViewModel();
//	model1.getAppReport();
 //      ko.applyBindings(model1);
	 
    
	});
});